import React, { useState, useEffect } from 'react';
import { useNavigate, useLocation } from 'react-router-dom';
import { Card, CardContent } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Progress } from '@/components/ui/progress';
import { useVocabulary } from '@/contexts/VocabularyContext';
import { selectRandomWords, shuffleArray, getWordCountByDifficulty } from '@/utils/gameHelpers';
import { ArrowLeft, Trophy, Clock } from 'lucide-react';
import type { Category } from '@/types/vocabulary';

interface FlipCard {
  id: string;
  content: string;
  type: 'english' | 'chinese';
  wordId: string;
  isFlipped: boolean;
  isMatched: boolean;
}

const MatchingGame: React.FC = () => {
  const navigate = useNavigate();
  const location = useLocation();
  const { getWordsByCategory, settings, updateMatchingStats, updateCategoryStats } = useVocabulary();
  const category = (location.state?.category as Category) || '全部类别';

  const [cards, setCards] = useState<FlipCard[]>([]);
  const [selectedCards, setSelectedCards] = useState<FlipCard[]>([]);
  const [matchedCount, setMatchedCount] = useState(0);
  const [matchedWords, setMatchedWords] = useState<string[]>([]);
  const [startTime, setStartTime] = useState<number>(0);
  const [elapsedTime, setElapsedTime] = useState(0);
  const [isGameComplete, setIsGameComplete] = useState(false);

  useEffect(() => {
    initializeGame();
  }, []);

  useEffect(() => {
    if (startTime > 0 && !isGameComplete) {
      const timer = setInterval(() => {
        setElapsedTime(Math.floor((Date.now() - startTime) / 1000));
      }, 1000);
      return () => clearInterval(timer);
    }
  }, [startTime, isGameComplete]);

  const initializeGame = () => {
    const allWords = getWordsByCategory(category);
    const wordCount = getWordCountByDifficulty(settings.difficulty);
    const selectedWords = selectRandomWords(allWords, wordCount);

    const gameCards: FlipCard[] = [];
    selectedWords.forEach((word) => {
      gameCards.push({
        id: `${word.id}-en`,
        content: word.english,
        type: 'english',
        wordId: word.id,
        isFlipped: false,
        isMatched: false,
      });
      gameCards.push({
        id: `${word.id}-zh`,
        content: word.chinese,
        type: 'chinese',
        wordId: word.id,
        isFlipped: false,
        isMatched: false,
      });
    });

    setCards(shuffleArray(gameCards));
    setSelectedCards([]);
    setMatchedCount(0);
    setMatchedWords([]);
    setElapsedTime(0);
    setIsGameComplete(false);
    setStartTime(Date.now());
  };

  const handleCardClick = (clickedCard: FlipCard) => {
    if (clickedCard.isMatched || clickedCard.isFlipped || selectedCards.length >= 2) {
      return;
    }

    const newCards = cards.map((card) =>
      card.id === clickedCard.id ? { ...card, isFlipped: true } : card
    );
    setCards(newCards);

    const newSelected = [...selectedCards, clickedCard];
    setSelectedCards(newSelected);

    if (newSelected.length === 2) {
      setTimeout(() => checkMatch(newSelected), 800);
    }
  };

  const checkMatch = (selected: FlipCard[]) => {
    const [card1, card2] = selected;

    if (card1.wordId === card2.wordId && card1.type !== card2.type) {
      const newCards = cards.map((card) =>
        card.wordId === card1.wordId ? { ...card, isMatched: true } : card
      );
      setCards(newCards);
      setMatchedCount((prev) => prev + 1);
      setMatchedWords([...matchedWords, card1.wordId]);

      const totalPairs = cards.length / 2;
      if (matchedCount + 1 === totalPairs) {
        const finalTime = Math.floor((Date.now() - startTime) / 1000);
        setElapsedTime(finalTime);
        setIsGameComplete(true);
        updateMatchingStats(finalTime);

        const words = getWordsByCategory(category);
        const word = words.find((w) => w.id === card1.wordId);
        if (word) {
          updateCategoryStats(word.category, true);
        }
      } else {
        const words = getWordsByCategory(category);
        const word = words.find((w) => w.id === card1.wordId);
        if (word) {
          updateCategoryStats(word.category, true);
        }
      }
    } else {
      const newCards = cards.map((card) =>
        selected.some((s) => s.id === card.id) ? { ...card, isFlipped: false } : card
      );
      setCards(newCards);
    }

    setSelectedCards([]);
  };

  const formatTime = (seconds: number) => {
    const mins = Math.floor(seconds / 60);
    const secs = seconds % 60;
    return `${mins}:${secs.toString().padStart(2, '0')}`;
  };

  const totalPairs = cards.length / 2;
  const progress = totalPairs > 0 ? (matchedCount / totalPairs) * 100 : 0;

  if (isGameComplete) {
    return (
      <div className="min-h-screen bg-gradient-to-br from-blue-50 via-white to-purple-50 flex items-center justify-center p-4">
        <Card className="max-w-md w-full">
          <CardContent className="pt-6">
            <div className="text-center space-y-6">
              <Trophy className="w-20 h-20 text-yellow-500 mx-auto" />
              <h2 className="text-3xl font-bold text-gray-900">恭喜完成！</h2>
              <div className="space-y-3">
                <div className="flex items-center justify-between text-lg">
                  <span className="text-gray-600">完成时间：</span>
                  <span className="font-semibold">{formatTime(elapsedTime)}</span>
                </div>
                <div className="flex items-center justify-between text-lg">
                  <span className="text-gray-600">配对数量：</span>
                  <span className="font-semibold">{matchedCount} 对</span>
                </div>
                <div className="flex items-center justify-between text-lg">
                  <span className="text-gray-600">得分：</span>
                  <span className="font-semibold text-green-600">
                    {Math.max(0, 100 - Math.floor(elapsedTime / 2))} 分
                  </span>
                </div>
              </div>
              <div className="flex gap-3">
                <Button onClick={() => navigate('/')} variant="outline" className="flex-1">
                  返回首页
                </Button>
                <Button onClick={initializeGame} className="flex-1">
                  再玩一次
                </Button>
              </div>
            </div>
          </CardContent>
        </Card>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gray-100 p-4">
      <div className="container mx-auto max-w-6xl">
        {/* 顶部导航栏 */}
        <div className="flex items-center justify-between mb-8">
          <Button variant="ghost" onClick={() => navigate('/')} className="bg-white hover:bg-gray-50">
            <ArrowLeft className="w-4 h-4 mr-2" />
            返回
          </Button>
          <div className="flex items-center gap-8">
            <div className="text-lg font-semibold">
              时间: {formatTime(elapsedTime)}
            </div>
            <div className="text-lg font-semibold">
              得分: {Math.max(0, 100 - Math.floor(elapsedTime / 2))}
            </div>
          </div>
        </div>

        {/* 游戏标题和说明 */}
        <div className="text-center mb-8">
          <h1 className="text-3xl font-bold text-gray-900 mb-3">单词配对游戏</h1>
          <p className="text-gray-600">翻转卡片，找出英文单词与中文释义的匹配对。</p>
        </div>

        {/* 卡片网格 */}
        <div className="grid grid-cols-5 gap-4 max-w-5xl mx-auto">
          {cards.map((card) => (
            <div
              key={card.id}
              className={`cursor-pointer transition-all duration-300 ${
                card.isMatched ? 'opacity-50' : 'hover:scale-105'
              }`}
              onClick={() => handleCardClick(card)}
            >
              <div
                className={`relative h-32 rounded-xl shadow-lg ${
                  card.isFlipped || card.isMatched
                    ? 'bg-gradient-to-br from-purple-500 to-purple-600'
                    : 'bg-gradient-to-br from-purple-600 to-purple-700'
                } flex items-center justify-center`}
              >
                {card.isFlipped || card.isMatched ? (
                  <div className="text-white font-semibold text-base text-center px-3 break-words">
                    {card.content}
                  </div>
                ) : (
                  <div className="text-white text-5xl">❓</div>
                )}
              </div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
};

export default MatchingGame;
